#include "pin_map_elite.h"
#include "stm32f10x.h"
/**
 * 定时器TIM2
 * 
*/
u16 sec;
void RCC_Configuration(void);
void GPIO_Configuration(void);
void TIM_Configuration(void);
void NVIC_Configuration(void);

int main() {
    RCC_Configuration();
    GPIO_Configuration();
    NVIC_Configuration();
    TIM_Configuration();

    while(1);

}

void RCC_Configuration() {
    SystemInit();
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE, ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
}

void GPIO_Configuration() {
    GPIO_InitTypeDef GPIO_InitStructure;

    // LED
    GPIO_InitStructure.GPIO_Pin = LED1_Pin;           //配置管脚5
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;  // IO口配置为推挽输出口
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOE, &GPIO_InitStructure);  //初始化PE5口

     GPIO_ResetBits(GPIOE, LED1_Pin); // LED初始灭
}

void TIM_Configuration() {
    TIM_TimeBaseInitTypeDef TIM_BaseInitStructure;

    TIM_BaseInitStructure.TIM_Prescaler = 0; 
    TIM_BaseInitStructure.TIM_ClockDivision = 0;
    TIM_BaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_BaseInitStructure.TIM_Period = 36000; // 预装值
    TIM_BaseInitStructure.TIM_RepetitionCounter = TIM_CKD_DIV1; // 滤波器采样分频
    TIM_TimeBaseInit(TIM2, &TIM_BaseInitStructure);
    TIM_UpdateRequestConfig(TIM2, TIM_UpdateSource_Regular); // 清中断, 以免一启用中断后立即产生中断
    // 使能TIM2中断源
    TIM_Cmd(TIM2, ENABLE);
    TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE); // TIM2 总开关: 开启
}

void NVIC_Configuration() {
    NVIC_InitTypeDef NVIC_InitStructure;

    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
    NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);

}

void TIM2_IRQHandler() {
    if (TIM_GetITStatus(TIM2, TIM_IT_Update) == SET) {
        if (++sec == 1000) {
            sec = 0;
             GPIOE->ODR ^= LED1_Pin;
        }
        TIM_ClearITPendingBit(TIM2, TIM_FLAG_Update);
    }
}
